package com.lkd.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lkd.dto.RegionDto;
import com.lkd.entity.Area;
import com.lkd.entity.Node;
import com.lkd.mapper.NodeMapper;
import com.lkd.mapper.RegionMapper;
import com.lkd.service.RegionService;
import com.lkd.entity.Region;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.vo.PageBean;
import com.lkd.vo.RegionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 运营区域 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-20
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    @Autowired
    private NodeMapper nodeMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public PageBean<RegionVo> findAreaByPage (String name, Integer pageIndex, Integer pageSize) {
        Page<Region> page = new Page<> (pageIndex, pageSize);

        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<> ();
        wrapper.like (StrUtil.isNotEmpty (name), Region::getName, name);

        page = getBaseMapper ().selectPage (page, wrapper);
        List<RegionVo> list = page.getRecords ().stream ().map (area -> {
            RegionVo areaVo = BeanUtil.copyProperties (area, RegionVo.class);
            LambdaQueryWrapper<Node> wrapper1 = new LambdaQueryWrapper<> ();
            wrapper1.eq (Node::getRegionId, area.getId ());
            areaVo.setNodeCount (nodeMapper.selectCount (wrapper1));

            return areaVo;
        }).collect (Collectors.toList ());

        return new PageBean<> (page, list);
    }

    @Override
    public boolean addRegion (RegionDto regionDto) {
        Region region = BeanUtil.copyProperties (regionDto, Region.class);
        region.setName (regionDto.getRegionName ());
        getBaseMapper ().insert (region);
        return true;
    }

    @Override
    public boolean updateRegion (RegionDto regionDto) {
        Region region = BeanUtil.copyProperties (regionDto,Region.class);
        region.setId (regionDto.getId ());
        region.setName (regionDto.getRegionName ());
        getBaseMapper ().updateById (region);
        return true;
    }



}
